//
//  ParserGML.java
//  TopoManipApplet
//
//  Created by Thibaud PIQUET on 23/03/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

package src.convertisseur;
import java.util.*;
import java.io.*;
import org.jdom.*;

/**
 *
 * @author Thibaud PIQUET
 * Version 1.1 - Ksoobrayen : Evolutions vers un fichier graphML --> Le 03 mars 2011
 */
public class ParserGML implements Runnable{
	
    File ftp; // File to parse
	File fileOut; // File to create
    Reader fr; // File Reader
    BufferedReader br; // Buffer Reader
    String line;
    String chaine;
    String[] res;

    String[] keyGraphNode = {"name","status", "switch", "location","form", "position"};
    String[] keyGraphEdge = {"status", "linkType" ,"bandwidth","metric"};
	
    public ParserGML(File file, File fileOUT) throws IOException {
        this.ftp = file;
		this.fileOut = fileOUT;
        this.fr = new FileReader(this.ftp);
        this.br = new BufferedReader(this.fr);
    }
	
	public void run() {
		try {
			this.parseToXML();
		}
		catch (Exception e) {
			e.printStackTrace();
			Resume result = Resume.getInstance();
			result.add("ParserGML","procedure run had some problems : "+e);
		}
	}
    
	public void parseToXML() throws IOException {

                Element graphml = new Element("graphml");
                Namespace nsGraphml = Namespace.getNamespace("http://graphml.graphdrawing.org/xmlns");
                graphml.setNamespace(nsGraphml);


                Element graph = new Element("graph");
                Attribute edgedefault = new Attribute("edgedefault", "undirected");
                graph.setAttribute(edgedefault);
		
		Element domain = new Element("domain");
		Element information = new Element("information");
		Element topology = new Element("topology");
		Element igp = new Element("igp");
		Element nodes = new Element("nodes");
		Element links = new Element("links");
		Element igpLinks = new Element("links");
		org.jdom.Document document = new Document(graphml);

		Resume result = Resume.getInstance();

		
		try {
			line = this.br.readLine();
			
			Element title = new Element("title");
			Element date = new Element("date");
			Element author = new Element("author");
			Element description = new Element("description");
			Date today = new Date();
			String day = "";
			String month = "";
			
			title.setText(fileOut.getName());
			if(today.getDate()<10) { day = "0"+today.getDate();} else { day = today.getDate()+""; }
			if((today.getMonth()+1)<10){ month = "0"+(today.getMonth()+1);} else { month = (today.getMonth()+1)+"";}
			date.setText((today.getYear()+1900)+"-"+month+"-"+day);
			author.setText("File Generator");
			description.setText("File generated by ParserGML from this jApplet");
			
			information.addContent(title);
			information.addContent(date);
			information.addContent(author);
			information.addContent(description);
			
			Element node = new Element("node");
			Element location = new Element("location");
			Element link = new Element("link");
			Element linkType = new Element("linkType");
			Element form = new Element("form");
			Element position = new Element("position");
                        Attribute nodename = null;
			
			
			String state = "";
			int counterIn = 0;
			int counterOut = 0;
			int counterLink = 0;

                        		
			while (line!=null){
				if (line!=null){
					if(line.startsWith("graph")) {
						// new graph
					}
					else if(line.contains("node")) {

                                            //System.out.println("Newww Nodes!!");
                                            state = "Node";
						counterIn = 0;
						counterOut = 0;
						
						node = new Element("node");
						counterIn++;
					}
					else if(line.contains("edge")) {
						counterLink++;
						counterIn = 0;
						counterOut = 0;					
						state = "Edge";
						
						link = new Element("edge");
						Attribute idLink = new Attribute("id",counterLink+"");
						link.setAttribute(idLink);
						
						counterIn++;
					}
					else {
                                            if(state.equals("Node")) {
                                                        //System.out.println(line.toString());
							res = line.split("\t");
                                                        /*for (int i=0 ; i< res.length; i++){
                                                            System.out.println("** "+i + "= "+ res[i]);

                                                        }*/

                                                       // System.out.println(line.toString());

                                                        /* id */
							if(Utils.checkPresence(res, "id")) {
                                                                Attribute idNode = new Attribute("id",Utils.getValuePosition(res, "id"));
								node.setAttribute(idNode);


							}
							
							/* name */
							else if(Utils.checkPresence(res, "label")) {
                                                                
                                                                Element NodeDescription = Utils.getNameNode("name", Utils.getValuePosition(res, "label").replace("\"", ""));
                                                                //Element NodeDescription = new Element("description");
								//Attribute label = new Attribute("label",Utils.getValuePosition(res, "label").replace("\"", ""));
								//NodeDescription.setAttribute(label);

                                                                node.addContent(NodeDescription);
								
								Element statusNode = Utils.getNameNode("status", "UP");
								node.addContent(statusNode);
								
								Element switchNode = Utils.getNameNode("switch", "false");
								node.addContent(switchNode);
							}
							
							else if(Utils.checkPresence(res, "graphics")) {
                                                                //System.out.println("333333333333333333333333333333333333333");
                                                                 location = new Element("data");
                                                                 nodename = new Attribute("key", "location");
                                                                 location.setAttribute(nodename);

                                                                 form = new Element("data");
                                                                 nodename = new Attribute("key", "form");
                                                                 location.setAttribute(nodename);


                                                                //location = new Element("location");
								//form = new Element("form");
								counterIn++;
							}
							
							else if(Utils.checkPresence(res, "center")) {
                                                                //System.out.println("44444444444444444444444444444444444444444");
								position = Utils.getNameNode("position", "centre");
                                                                counterIn++;
							}
							
							else if(Utils.checkPresence(res, "x")) {
								Attribute xCoordonate =  new Attribute("x",Utils.getValuePosition(res, "x"));
								location.setAttribute(xCoordonate);
							}
							else if(Utils.checkPresence(res, "y")) {
								Attribute yCoordonate =  new Attribute("y",Utils.getValuePosition(res, "y"));
                                                                location.setAttribute(yCoordonate);
							}
							else if(Utils.checkPresence(res, "z")) {
								Attribute zCoordonate =  new Attribute("z",Utils.getValuePosition(res, "z"));
								location.setAttribute(zCoordonate);
							}
							else if(Utils.checkPresence(res, "w")) {
								Attribute wCoordonate =  new Attribute("w",Utils.getValuePosition(res, "w"));
								location.setAttribute(wCoordonate);
							}
							else if(Utils.checkPresence(res, "h")) {
								Attribute hCoordonate =  new Attribute("h",Utils.getValuePosition(res, "h"));
								location.setAttribute(hCoordonate);
							}                        
							else if(Utils.checkPresence(res, "d")) {
								Attribute dCoordonate =  new Attribute("d",Utils.getValuePosition(res, "d"));
								location.setAttribute(dCoordonate);
							}
							else if(Utils.checkPresence(res, "image")) {
								Attribute image =  new Attribute("d",Utils.getValuePosition(res, "image"));
								form.setAttribute(image);
							}
							else if(Utils.checkPresence(res, "outlineColor")) {
								Attribute outlineColor =  new Attribute("d",Utils.getValuePosition(res, "outlineColor"));
								form.setAttribute(outlineColor);
								//System.out.println("d = "+1]);
							}
							else if(Utils.checkPresence(res, "forme")) {
								Attribute forme =  new Attribute("d",Utils.getValuePosition(res, "forme"));
								form.setAttribute(forme);
							}
							else if(Utils.checkPresence(res, "fillColor")) {
								Attribute fillColor =  new Attribute("d",Utils.getValuePosition(res, "fillColor"));
								form.setAttribute(fillColor);
							}
							else if(Utils.checkPresence(res, "]")) {
                                                            //System.out.println("]]]]]]]]]]]]");
								counterOut++;
								if((counterIn-counterOut)==1) {
									node.addContent(location);
									if(!position.getText().equals("")){
										node.addContent(position);
									}
									if(form.getAttributes().size()!=0){
										node.addContent(form);
									}
								}
								if((counterIn-counterOut)==0) {
									if(!("UP").equals(Utils.getValueNode("status", node))) {
										Element statusNode = Utils.getNameNode("status", "UP");
										
										node.addContent(statusNode);
									}
									if(! ("false").equals(Utils.getValueNode("switch", node))) {
										Element switchNode = Utils.getNameNode("switch", "false");
										node.addContent(switchNode);
									}
									
									nodes.addContent(node);
								}
							}
						}
						else if(state.equals("Edge")) {
							res = line.split("\t");
							
							/* source */
							if(Utils.checkPresence(res, "source")) {
								//Element source = new Element("source");
								Attribute srcNode = new Attribute("source",Utils.getValuePosition(res, "source"));
								
								link.setAttribute(srcNode);
								//link.addContent(source);
							}
							/* target */
							else if(Utils.checkPresence(res, "target")) {
								//Element target = new Element("target");
								Attribute tgtNode = new Attribute("target",Utils.getValuePosition(res, "target"));
								
								link.setAttribute(tgtNode);
								//link.addContent(target);
								
								Element statusLink = Utils.getNameNode("status", "UP");
								link.addContent(statusLink);
							}
							/* simplex : type */
							else if(Utils.checkPresence(res, "simplex")) {
								String resultT = "";
								if(Integer.parseInt(Utils.getValuePosition(res, "simplex"))==1) {
                                                                    resultT="simplex";
                                                                }
                                                                linkType = Utils.getNameNode("linkType", resultT);


							}
							/* duplex : type */
							else if(Utils.checkPresence(res, "duplex")) {
								
								String resultT = "";
								if(Integer.parseInt(Utils.getValuePosition(res, "duplex"))==1) { resultT="duplex";}

                                                                linkType = Utils.getNameNode("linkType", resultT);
							}
							/* bandwidth and adding linkType*/
							else if(Utils.checkPresence(res, "bandwidth")) {
								Element bandwidth = Utils.getNameNode("bandwidth", Utils.getValuePosition(res, "bandwidth"));
								link.addContent(bandwidth);
								link.addContent(linkType);
							}
							/* metric */
							else if(Utils.checkPresence(res, "metric")) {
                                                                //System.out.println("metric founddddd!!");
								Element metric = Utils.getNameNode("metric", Utils.getValuePosition(res, "metric"));
                                                                link.addContent(metric);
							}
							else if(Utils.checkPresence(res, "]")) {
								counterOut++;
								if((counterIn-counterOut)==0) {
									links.addContent(link);
								}
							}
						}
					}
					
					
				}
				line = this.br.readLine();
			}
			br.close();
			fr.close();

                        for (int i = 0; i < keyGraphNode.length; i++) {
                            topology.addContent(Utils.getKeyGraph(i, keyGraphNode, "node"));

                        }

                        for (int i = 0; i < keyGraphEdge.length; i++) {
                            topology.addContent(Utils.getKeyGraph(i, keyGraphEdge, "edge"));

                        }
                        
			topology.addContent(nodes);
			topology.addContent(links);
			
			domain.addContent(information);
			domain.addContent(topology);

                        graph.addContent(domain);
                        graphml.addContent(graph);
			
			org.jdom.output.XMLOutputter sortie = new org.jdom.output.XMLOutputter(org.jdom.output.Format.getPrettyFormat());
			sortie.output(document, new FileOutputStream(fileOut.getAbsolutePath()));
			
			result.add("ParserGML","Import succeeded");
			
		} catch (Exception e) {
			e.printStackTrace();
			result.add("ParserGML","Import had problems "+e);
		}
	}
}
